/*
 * Created on Oct 27, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.erclab.internal.xpresso.handlers;

import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.formelements.*;

import java.util.*;
import java.sql.*;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.RowProcessor;

/**
 * @author rodrigen
 *
 */
public class FormElementHandler implements ResultSetHandler {

	public FormElementHandler() {
	}
	
	private void setFormElementProperties(FormElement fe, ResultSet rs) throws SQLException{
		fe.setIdFormElement(rs.getInt("IdFormElement"));
		fe.setDisplayOrder(rs.getInt("DisplayOrder"));
		fe.setDestinationTable(rs.getString("DestinationTable"));
		fe.setDestinationColumn(rs.getString("DestinationColumn"));
		fe.setDataType(rs.getString("DataType"));
		fe.setDescription(rs.getString("Description"));
		fe.setClassHandler(rs.getString("ClassHandler"));
		fe.setLabel(rs.getString("Label"));
		fe.setLookupQuery(rs.getString("LookupQuery"));
		fe.setLookupDataSourceId(rs.getInt("lookupDataSourceId"));
		fe.setParameters(rs.getString("Parameters"));
		fe.setStyle(rs.getString("Style"));
		fe.setDestinationDataSourceId(rs.getInt("DestinationDataSourceId"));
		fe.setRequired(rs.getBoolean("Required"));
		
	}

	public Object handle(ResultSet rs) throws SQLException  {
		ArrayList formElements = new ArrayList();
		while (rs.next()){
			String classHandler = rs.getString("classHandler");
			FormElement fe = null;
			try {
				Class formElementClass = Class.forName(classHandler);
				fe = (FormElement) formElementClass.newInstance();
				// Set values of the form element by calling the setters
				this.setFormElementProperties(fe, rs);
			} catch(ClassNotFoundException e){
				throw new SQLException("The class: " + classHandler + " could not be found." + e);
			} catch(IllegalAccessException e){
				throw new SQLException("IllegalAccessException: " + e);
			} catch(InstantiationException e){
				throw new SQLException("InstantiationException" + e);				
			}

			formElements.add(fe);
				
		}
		return formElements;
	}	


}
